//
//  ShoppingCartViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/11.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class ShoppingCartViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, ShoppingCartTableViewCellDelegate,BottomShadow,AddCornerUIRectCorner {
    
    let CellHeight: CGFloat = 110
    @IBOutlet weak var doneButton: UIButton!
    @IBOutlet weak var totalPriceLabel: UILabel!
    @IBOutlet weak var mainTableView: UITableView!
    @IBOutlet weak var popularizeCollectionView: ConsultationCollectionView!
    
    
    var models: [cartModel] = []
    var carIds: [String] = []
    var totalAmount: Float = 0
    private var recommendData: [GoodsModel] = []
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var page:Int = 0
    var totalPage:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.titleLabel(text: "我的购买", nil)
        totalPriceLabel.text = "0"
        mainTableView.register(UINib(nibName: "\(ShoppingCartTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
//        popularizeCollectionView.setData()
        
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        mainTableView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
    
        self.headerRefresh()
        popularizeCollectionView.contentOffset = .zero
        popularizeCollectionView.delegateVc = self
        
        self.fetchRecommendProductList()
        // Do any additional setup after loading the view.
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()
        
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        self.fetchCartList(parameters: ["page":page,"pageSize":10])
      
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
       
    }
    override func setNavigation() {}
    
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.models.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ShoppingCartTableViewCell
        cell?.bindData(model: models[indexPath.row],index: indexPath.row)
        cell?.delegate = self
        cell?.delegate2 = self
        cell?.deleteblock = {
            self.models.remove(at: indexPath.row)
            self.mainTableView.reloadData()
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CellHeight
    }
  
    @IBAction func selectAllTap(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if !sender.isSelected {
            self.totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString: "0", secondColor: ONColor.pirceLabelColor, secondSize: 16))
        }
        let count : Int = models.count - 1
        totalAmount = 0
        for index in 0...count {
            let cell : ShoppingCartTableViewCell = self.mainTableView.cellForRow(at: NSIndexPath(row: index, section: 0) as IndexPath) as! ShoppingCartTableViewCell
            cell.selectBtn.isSelected = sender.isSelected
            if sender.isSelected {
                models[index].selected = "1"
                self.addAmount(index: index)
            }else {
                models[index].selected = "0"
            }
        }
    }
    
    @IBAction func doneTap(_ sender: UIButton) {
        carIds.removeAll()
        for model in models {
            if model.selected == "1" {
                carIds.append(model.id!)
            }
        }
        if carIds.count > 0 {
            let buyNowVC = BuyNowViewController(nibName: "\(BuyNowViewController.self)", bundle: nil)
            buyNowVC.carIds = carIds
            buyNowVC.type = 1
            self.navigationController?.pushViewController(buyNowVC, animated: true)
        }
    }
    
    func addAmount(index: Int) {
        let model = models[index]
        let price :Float = Float(model.price!)!
        let number :Float = Float(model.number!)!
        let total :Float = price * number
        totalAmount += total
        
        self.totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString: String(format: "%.2f", abs(totalAmount)) as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
    }
    
    func mulAmount(index: Int) {
        let model = models[index]
        let price :Float = Float(model.price!)!
        let number :Float = Float(model.number!)!
        let total :Float = price * number
        totalAmount -= total
        
        self.totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString: String(format: "%.2f", abs(totalAmount)) as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
    }
    
    func selectCell(index: Int, flag: Bool) {
        let model = models[index]
        let price :Float = Float(model.price!)!
        let number :Float = Float(model.number!)!
        let total :Float = price * number
        if flag {
            totalAmount += total
            models[index].selected = "1"
        }else {
            totalAmount -= total
            models[index].selected = "0"
        }
        self.totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString: String(format: "%.2f", abs(totalAmount)) as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
    }
    
    /// 获取商品列表
    func fetchCartList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(cartListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.models.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        var price: Float = 0
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = cartModel(fromDic: dic)
                                            let json = JSON(model.price)
                                            price += json.floatValue
                                            self.models.append(model)
                                        }
                                        if self.totalPage == self.models.count{
                                            self.mainTableView.mj_footer = nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 获取推荐商品列表数据
    func fetchRecommendProductList() -> Void {
        let requesturl = "\(BaseURL)\(recommendShoppingListUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: nil ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        self.recommendData.removeAll()
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            
                                            var model = GoodsModel(fromDic: dic)
                                            model.type = "4"
                                            self.recommendData.append(model)
                                        }
                                        
                                        self.popularizeCollectionView.setData(arr: self.recommendData)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    func delCell(id:String,cell:ShoppingCartTableViewCell) -> Void {
        let alertController = UIAlertController(title: "删除商品？", message: nil, preferredStyle: .alert)
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: { (_) in
            
        })
        let sureAction = UIAlertAction.init(title: "确定", style: .default, handler: { (_) in
            var url = appendUrl(suffix: delCar)
            let parameter:[String : String] = ["id": id]
            Alamofire.request(url, method: .get,
                              parameters: parameter,
                              encoding: URLEncoding.default,
                              headers: nil).responseJSON {
                                (response) in
                                
                                if(response.error == nil){
                                    if let result = response.result.value as? NSDictionary
                                    {
                                        
                                        let json = JSON(result)
                                        if json["code"].int == 1{
                                            self.showToast(msg:json["message"].stringValue)
                                            cell.deleteblock!()
                                        }
                                        else{
                                            self.showToast(msg:json["message"].stringValue)
                                        }
                                    }
                                }else{
                                    self.showToast(msg:"删除失败")
                                }
                                
            }
        })
        alertController.addAction(cancel)
        alertController.addAction(sureAction)
        self.present(alertController, animated: true, completion: nil)
    }
}
